#!/usr/bin/env python

import os, pm, vm
import log
import commands
import re
import subprocess as sp

# Sets up SigLM resource monitoring on PM
def Setup():
	
#	p_dir = sp.Popen('echo $HOME',shell=True,stdout=sp.PIPE)
#    	homeDir = re.sub("\s+",'',p_dir.communicate()[0])
	
	outputPath = '/siglmLogs'
	if not os.path.exists(outputPath):
		os.system('mkdir ' + outputPath)

	os.chdir(outputPath)
	commands.getoutput('cp -r /vm/siglm/msrc/xen_resource_log .')
	commands.getoutput('tar -xvf xen_resource_log.tar')

    	os.chdir('./xen_resource_log')
    	#commands.getoutput('make clean;make')
	
	host_sp = sp.Popen('echo $HOSTNAME',shell=True,stdout=sp.PIPE)
        hostname = re.sub("\s+",'',host_sp.communicate()[0])
        if 'csc.ncsu.edu' not in hostname:
        	hostname += '.csc.ncsu.edu'

    	p_siglm = sp.Popen('./xen_resource_log_d ' + hostname, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
 	
    	return True


# Write the current PM's to /vm/siglm/src/map/hosts.txt
def WritePMList ( pmList ):
	
	# Print
	log.write('Writing hosts to SigLM')
	
	# Open hosts file
	FILE = open('/vm/siglm/src/map/hosts.txt','w')
	
	# Write all hostnames in PM to file
	for thisPM in pmList:
		FILE.write(thisPM.IP + '\n')
	
	# Close the file
	FILE.close()
	
	# Print
	log.write('Wrote hosts to SigLM')

# Write a list of VMs to /vm/siglm/src/map/vms.txt
def WriteVMList (vmList):

	# Print
	log.write( 'Writing VMs to SigLM')
	
	# Open vm file
	FILE = open('/vm/siglm/src/map/vms.txt','w')
	
	# Write all hostnames in PM to file
	for thisVM in vmList:
		FILE.write(thisVM.domainCfgVars['name'] + '\n')
	
	# Close the file
	FILE.close()
	
	# Print
	log.write( 'Wrote VMs to SigLM')

# Get a batch of host recommendations
def GetHosts ( vmList,pmList ):
	
	# Write lists to file
	WritePMList (pmList)
	WriteVMList (vmList)
	
	# Run siglm
	os.system('/vm/siglm/src/map/getoutput.py')

	# Open output file
	FILE = open('/vm/siglm/src/map/pyoutput.txt','r')
	
	# Parse siglm output into dictionary
	sigLMOutput = {}
	for line in FILE.readlines():
		
		# Parse the line
		pmHostname = line.split('|')[0].strip()
		vmHostname = line.split('|')[1].strip()
		
		# Add to dictionary
		sigLMOutput[vmHostname] = pmHostname
	
	# Return dictionary
	return sigLMOutput
